/**
 * 系统后台多表夸库查询服务JS-SingleTableService.jsp
 */
var {pinyin} = pinyinPro;
var operation = {};
var postPath = '/gdp'
var app = new Vue({
    el: '#main-container',
    data: {
        serviceIdOptStatus: false,

        // saveStatus:[false,false,false],

        // 服务信息配置
        cfgInfo: {
            // 名称
            servicename: "",
            // 服务id
            servicecode: "",
            // 说明
            remark: "",
            // 是否分页
            paginationFlag: 1,
            // 服务类型s
            servicetype: "",
            // 项目编码
            pcode: ""

        },


        relInfo: {
            cfgMultRelation: {
                relationId: "",
                // 服务id
                serviceId: null,
                // 服务1
                firstServiceId: "",
                // 服务2
                secondServiceId: "",
                // 关联方式
                condition: ""
            },
            // 选中的关联字段集合
            fieldList: [
                {
                    relationFieldId: "",
                    firstFieldId: "",
                    secondFieldId: "",
                    firstFieldCode: "",
                    secondFieldCode: ""
                }
            ],
            delRelFieldList: []
        },

        delRelFieldList: [],
        // 服务1集合下拉
        service1List: [],
        // 服务2集合下拉
        service2List: [],
        // 字段1集合
        filed1List: [],
        // 字段2集合
        filed2List: [],


        selectedServiceInfo: [{}, {}],
        // 服务1 服务2 参数集合
        serviceParamList: [],
        serviceParamTmpList: [],
        tmpRightServiceParamMap: {},
        tmpEmpParam: {},
        // 服务1 服务2 显示列集合
        serviceResList: [],
        serviceResTmpList: [],
        tmpRightServiceResMap: {},


        // 字段1集合
        resFiled1List: [],
        // 字段2集合
        resFiled2List: [],
        displayRules: [],
        // 字典
        dict: {

            // 关联方式
            relTypeList: [
                {k: "INNER_JOIN", v: "INNER JOIN"},
                {k: "LEFT_JOIN", v: "LEFT JOIN"},
                {k: "RIGHT_JOIN", v: "RIGHT JOIN"},
                {k: "FULL_JOIN", v: "FULL JOIN"}
            ],
            displayRules: [],
        },
        loadingPage: true
    },
    computed: {
        polymServiceParamList: function () {
            let newArr = [];
            let obj = {};
            for (let i = 0; i < this.serviceParamList.length; i++) {
                if (this.serviceParamList[i].status == 'Y' && !obj[this.serviceParamList[i].newFieldCode]) {
                    newArr.push(this.serviceParamList[i]);
                    obj[this.serviceParamList[i].newFieldCode] = true
                }
            }
            return newArr;
        },


        polymServiceResList: function () {
            let newArr = [];
            let obj = {};
            for (let i = 0; i < this.serviceResList.length; i++) {
                if (this.serviceResList[i].status == 'Y' && !obj[this.serviceResList[i].newFieldCode]) {
                    newArr.push(this.serviceResList[i]);
                    obj[this.serviceResList[i].newFieldCode] = true
                }
            }
            return newArr;
        },


        conditionPolymServiceResList: function () {
            let newArr = [];
            let obj = {};
            let codeNameMap = {};

            for (let i = 0; i < this.serviceResList.length; i++) {
                if (this.serviceResList[i].status == 'Y') {

                    let times = obj[this.serviceResList[i].newFieldCode];
                    if (!times) {
                        // 将字段名称放在map中
                        codeNameMap[this.serviceResList[i].newFieldCode] = this.serviceResList[i].newFieldName
                        obj[this.serviceResList[i].newFieldCode] = times = 1
                    } else {
                        obj[this.serviceResList[i].newFieldCode] = ++times;
                    }

                    if (times == 2) {

                        if (!this.serviceResList[i].condition) {
                            this.serviceResList[i].condition = ''
                        }
                        // 永远取第一个的字段名称
                        let ele = this.serviceResList[i];
                        // 拷贝一下
                        let newObj = JSON.parse(JSON.stringify(ele))
                        newObj.newFieldName = codeNameMap[this.serviceResList[i].newFieldCode]
                        newArr.push(newObj);
                    }


                }
            }
            return newArr;
        }


    },

    created: function () {

    },

    watch: {
        "relInfo.cfgMultRelation.firstServiceId": function (n, o) {
            // this.filed1List = this.getFieldList(n);
            this.resFiled1List = this.getResFieldList(n)
        },

        "relInfo.cfgMultRelation.secondServiceId": function (n, o) {
            // this.filed2List = this.getFieldList(n);
            this.resFiled2List = this.getResFieldList(n)
        },
        "cfgInfo.servicename": function (n, o) {
            let operate = this.getQueryString("operate");
            // 新增的时候才能走下面的逻辑
            if (operate != 'edit'){
                let charArr = pinyin(n, {pattern: 'first', type: 'array'})
                let str = ''
                charArr.forEach(c => {
                    if (c) str += c;
                })
                this.cfgInfo.servicecode = str;
            }
        },
    },
    mounted: function () {
        this.initData();
    },
    methods: {


        initData() {
            this.tmpRightServiceParamMap = {};
            this.cfgInfo.servicetype = this.getQueryString("servertype");
            this.cfgInfo.pcode = this.getQueryString("projectid");
            let servercode = this.getServiceCode("servercode");
            this.getServerList();
            if (servercode) this.getCfgInfo(servercode);
            this.getParamsInfo();
            this.initParamList();
            this.getResInfo();
            this.initResList();
        },

        getServiceCode() {
            if (!this.cfgInfo.servicecode) {
                this.cfgInfo.servicecode = this.getQueryString("servercode");
            }
            return this.cfgInfo.servicecode;
        },


        initResList() {
            let _this = this
            let firstServiceId = this.relInfo.cfgMultRelation.firstServiceId;
            let secondServiceId = this.relInfo.cfgMultRelation.secondServiceId;
            this.serviceResList = []
            _this.resFiled1List = _this.getResFieldList(firstServiceId)
            _this.resFiled1List.forEach(item => _this.filterResList(item))

            _this.resFiled2List = _this.getResFieldList(secondServiceId)
            _this.resFiled2List.forEach(item => _this.filterResList(item))
        },


        initParamList() {
            let _this = this
            let firstServiceId = this.relInfo.cfgMultRelation.firstServiceId;
            let secondServiceId = this.relInfo.cfgMultRelation.secondServiceId;
            let ser1 = this.service1List.filter(i => i.guid === firstServiceId);
            let ser2 = this.service2List.filter(i => i.guid === secondServiceId);
            if (ser1 && ser1[0]) {
                this.selectedServiceInfo[0] = {serviceId: firstServiceId, serviceName: ser1[0].servicename}

            }
            if (ser2 && ser2[0]) {
                this.selectedServiceInfo[1] = {serviceId: secondServiceId, serviceName: ser2[0].servicename}
            }

            this.serviceParamList = []
            // 拿到参数并过滤
            this.filed1List = this.getFieldList(firstServiceId);

            this.filed1List.forEach(item => _this.filterList(item))

            // 拿到参数并过滤
            this.filed2List = this.getFieldList(secondServiceId);
            this.filed2List.forEach(item => _this.filterList(item))

            // {k: "LEFT", v: "仅取服务1的字段"},
            // {k: "RIGHT", v: "仅取服务2的字段"},
            // {k: "NOT_NULL_LEFT", v: "优先取有数据字段,否则取服务1的字段"},
            // {k: "NOT_NULL_RIGHT", v: "优先取有数据字段,否则取服务2的字段"}
            this.dict.displayRules = [];
            this.dict.displayRules.push({k: "LEFT", v: "仅取" + this.selectedServiceInfo[0].serviceName + "的字段"});
            this.dict.displayRules.push({k: "RIGHT", v: "仅取" + this.selectedServiceInfo[1].serviceName + "的字段"});
            this.dict.displayRules.push({
                k: "NOT_NULL_LEFT",
                v: "优先取有数据字段,否则取" + this.selectedServiceInfo[0].serviceName + "的字段"
            });
            this.dict.displayRules.push({
                k: "NOT_NULL_LEFT",
                v: "优先取有数据字段,否则取" + this.selectedServiceInfo[1].serviceName + "的字段"
            });

        },


        filterList(item) {
            let _this = this
            // 把已经选中的筛选出来 改状态
            let selList = this.serviceParamTmpList.filter(i => item.guid === i.sourceFieldId && item.parametercode === i.sourceFieldCode);
            if (selList) {
                selList.forEach(sel => {
                    sel.status = 'Y';
                    this.serviceParamList.push(sel);
                })
            }
            if (selList.length === 0) {
                this.serviceParamList.push({
                    serviceId: _this.cfgInfo.guid,
                    sourceServiceId: item.serviceguid,
                    sourceFieldId: item.guid,
                    sourceFieldCode: item.parametercode,
                    status: "N"
                })
            }
        },


        filterResList(item) {
            let _this = this
            // 把已经选中的筛选出来 改状态
            let selList = this.serviceResTmpList.filter(i => item.guid === i.sourceFieldId && item.fieldname === i.sourceFieldCode);
            if (selList && selList.length > 0) {
                selList.forEach(sel => {
                    sel.status = 'Y';
                    this.serviceResList.push(sel);
                })
            }
            if (selList.length === 0) {
                this.serviceResList.push({
                    serviceId: _this.cfgInfo.guid,
                    sourceServiceId: item.serviceguid,
                    sourceFieldId: item.guid,
                    sourceFieldCode: item.fieldname,
                    status: "N"
                })
            }
        },


        disableCodeInput(opt) {
            if (opt === 'edit') {
                this.serviceIdOptStatus = true;
            }
        },

        setField1Code(o) {
            let fieldListElement = this.relInfo.fieldList[o];
            let ts = this.resFiled1List.filter(i => i.fieldname == fieldListElement.firstFieldCode);
            if (ts && ts[0]) {
                let t = ts[0];
                fieldListElement.firstFieldId = t.guid
            }
        },

        setField2Code(o) {
            let fieldListElement = this.relInfo.fieldList[o];
            let ts = this.resFiled2List.filter(i => i.fieldname == fieldListElement.secondFieldCode);
            if (ts && ts[0]) {
                let t = ts[0];
                fieldListElement.firstFieldId = t.guid
            }
        },

        //获取Query参数
        getQueryString: function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        },


        getCfgInfo(servercode) {
            let _this = this;

            $.ajax({
                type: 'POST',
                url: postPath + '/system/polym/getPolymInfo',
                data: JSON.stringify({"servercode": servercode}),
                dataType: 'json',
                contentType: 'application/json;charset=UTF-8',
                async: false,
                success: function (res) {
                    if (res.success) {
                        _this.cfgInfo = res.data.cfgInfo;
                        _this.relInfo = res.data.relInfo;

                    } else {
                        showMsg("操作失败,请稍后重试!", "error");
                    }
                }
            });
        },


        getServerList() {
            let _this = this;

            $.ajax({
                type: 'POST',
                url: postPath + '/system/polym/serverList',
                data: JSON.stringify({}),
                dataType: 'json',
                contentType: 'application/json;charset=UTF-8',
                async: false,
                success: function (res) {
                    if (res.success) {
                        _this.service1List = res.data;
                        _this.service2List = res.data;

                    } else {
                        showMsg("操作失败,请稍后重试!", "error");
                    }
                }
            });


        },


        getFieldList(id) {

            let resList = [];
            $.ajax({
                type: 'POST',
                url: postPath + '/system/polym/getParamsById',
                data: JSON.stringify({"serviceId": id}),
                dataType: 'json',
                async: false,
                contentType: 'application/json;charset=UTF-8',
                success: function (res) {
                    if (res.success) {
                        resList = res.data
                    } else {
                        showMsg("操作失败,请稍后重试!", "error");
                    }
                }
            });
            return resList;
        },


        getResFieldList(id) {

            let resList = [];
            $.ajax({
                type: 'POST',
                url: postPath + '/system/polym/getResById',
                data: JSON.stringify({"serviceId": id}),
                dataType: 'json',
                async: false,
                contentType: 'application/json;charset=UTF-8',
                success: function (res) {
                    if (res.success) {
                        resList = res.data
                    } else {
                        showMsg("操作失败,请稍后重试!", "error");
                    }
                }
            });
            return resList;
        },


        moveLeft(item, i) {
            this.clearNewCodeIfNull(item)
            let index;
            let f = this.serviceParamList.filter((p, idx) => {
                if (p.sourceFieldId === item.sourceFieldId) {
                    index = idx
                    return true;
                }
                return false;
            });
            if (f && f[0]) {
                this.$set(this.serviceParamList[index], 'status', 'N')
                this.serviceParamList.splice(index, 1, this.serviceParamList[index])

            }
        },
        moveRight(item, opt) {
            if(!this.setNewCodeIfNull(item)) return;
            let index;
            let f = this.serviceParamList.filter((p, idx) => {
                if (p.sourceFieldId === item.sourceFieldId) {
                    index = idx
                    return true;
                }
                return false;
            });
            if (f && f[0]) {
                this.$set(this.serviceParamList[index], 'status', 'Y')
                this.serviceParamList.splice(index, 1, this.serviceParamList[index])

            }
        },

        setNewCodeIfNull(item) {
            // 当新字段Code为空的时候 就将老字段的Code赋值给新字段 并记录下来 等到取消勾选的时候再进行清空新字段
            if (!item.newFieldCode) {
                this.tmpEmpParam[item.sourceFieldId] = true;
                item.newFieldCode = item.sourceFieldCode;
            }


            if (this.tmpRightServiceParamMap[item.newFieldCode + item.sourceServiceId]) {
                showMsg("同一个服务中新字段Code不能重复!", "error");
                return false;
            }
            this.tmpRightServiceParamMap[item.newFieldCode + item.sourceServiceId] = true;
            return true;
        },

        clearNewCodeIfNull(item) {
            this.tmpRightServiceParamMap[item.newFieldCode + item.sourceServiceId] = false;
            // 如果集合中有此元素 则证明是自动给新字段赋值
            if (this.tmpEmpParam[item.sourceFieldId]) {
                this.tmpEmpParam[item.sourceFieldId] = false;
                // item.newFieldCode = '';
            }
        },


        moveResLeft(item, i) {
            this.clearNewCodeIfNull(item);
            let index;
            let f = this.serviceResList.filter((p, idx) => {
                if (p.sourceFieldId === item.sourceFieldId) {
                    index = idx
                    return true;
                }
                return false;
            });
            if (f && f[0]) {
                this.$set(this.serviceResList[index], 'status', 'N')
                this.serviceResList.splice(index, 1, this.serviceResList[index])

            }
        },
        moveResRight(item, opt) {
            if(!this.setNewCodeIfNull(item)) return;
            let index;
            let f = this.serviceResList.filter((p, idx) => {
                if (p.sourceFieldId === item.sourceFieldId) {
                    index = idx
                    return true;
                }
                return false;
            });
            if (f && f[0]) {
                this.$set(this.serviceResList[index], 'status', 'Y')
                this.serviceResList.splice(index, 1, this.serviceResList[index])

            }
        },
        /**
         * 保存配置信息
         */
        saveCfgInfo() {
            let _this = this;
            _this.relInfo.cfgMultRelation.serviceCode = _this.cfgInfo.servicecode;
            _this.relInfo.delRelFieldList = _this.delRelFieldList;

            let params = {
                "cfgInfo": _this.cfgInfo,
                "relInfo": _this.relInfo,
            }

            $.ajax({
                type: 'POST',
                url: postPath + '/system/polym/saveCfgInfo',
                data: JSON.stringify(params),
                dataType: 'json',
                async: false,
                contentType: 'application/json;charset=UTF-8',
                success: function (res) {
                    if (res.success) {
                        showMsg("操作成功!", "success");
                    } else {
                        showMsg("操作失败,请稍后重试!", "error");
                    }
                }
            });


        },

        /**
         * 参数信息
         */
        saveParamsInfo() {
            let _this = this;
            if (this.serviceParamList) {
                let yList = this.serviceParamList.filter(i => i.status === "Y");
                $.ajax({
                    type: 'POST',
                    url: postPath + '/system/polym/saveParamsInfo',
                    data: JSON.stringify({serviceId: this.cfgInfo.guid, list: yList}),
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    success: function (res) {
                        if (res.success) {
                            showMsg("操作成功!", "success");
                            _this.getParamsInfo();
                            _this.initParamList();
                        } else {
                            showMsg("操作失败,请稍后重试!", "error");
                        }
                    }
                });


            }
        },


        /**
         * 查询参数信息
         */
        getParamsInfo() {
            let _t = this;
            if (!this.cfgInfo.guid) return;
            $.ajax({
                type: 'POST',
                url: postPath + '/system/polym/getParamsInfo',
                data: JSON.stringify({serviceId: this.cfgInfo.guid}),
                dataType: 'json',
                contentType: 'application/json;charset=UTF-8',
                async: false,
                success: function (res) {
                    if (res.success) {
                        _t.serviceParamTmpList = res.data;
                    } else {
                        showMsg("操作失败,请稍后重试!", "error");
                    }
                }
            });


        },

        /**
         * 保存显示列信息
         */
        saveResInfo() {
            let _this = this;
            if (this.serviceResList) {
                let yList = this.serviceResList.filter(i => i.status === "Y");
                yList.forEach(y => {
                    let cond = this.conditionPolymServiceResList.filter(p => p.newFieldCode == y.newFieldCode);
                    if (cond && cond[0]) {
                        y.condition = cond[0].condition;
                    }
                })


                $.ajax({
                    type: 'POST',
                    url: postPath + '/system/polym/saveResInfo',
                    data: JSON.stringify({serviceId: this.cfgInfo.guid, list: yList}),
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    success: function (res) {
                        if (res.success) {
                            showMsg("操作成功!", "success");
                            _this.getResInfo();
                            _this.initResList();
                        } else {
                            showMsg("操作失败,请稍后重试!", "error");
                        }
                    }
                });
            }
        },


        /**
         * 查询参数信息
         */
        getResInfo() {
            let _t = this;
            $.ajax({
                type: 'POST',
                url: postPath + '/system/polym/getResInfo',
                data: JSON.stringify({serviceId: this.cfgInfo.guid}),
                dataType: 'json',
                contentType: 'application/json;charset=UTF-8',
                async: false,
                success: function (res) {
                    if (res.success) {
                        _t.serviceResTmpList = res.data;
                    } else {
                        showMsg("操作失败,请稍后重试!", "error");
                    }
                }
            });


        },

        /**
         * 新增关联
         */
        addRel: function () {
            var _this = this;
            _this.relInfo.fieldList.push({
                relationFieldId: "",
                firstFieldId: "",
                secondFieldId: "",
                firstFieldCode: "",
                secondFieldCode: ""
            })
        },
        /**
         * 删除关联
         */
        delRel: function (idx) {
            let _this = this;
            let relationFieldId = _this.relInfo.fieldList[idx].relationFieldId;
            _this.delRelFieldList.push(relationFieldId);
            _this.relInfo.fieldList.splice(idx, 1)
        },
        /**
         * 页签点击事件
         */
        tabClick: function (idx) {
            this.initData();
        },
        /**
         * 返回按钮
         */
        backBtn() {
            window.location.href = postPath + "/prjService/index"
        },
        //搜索
        doSearch: function () {
            this.getNewData();
        }
    }
})


function showMsg(text, icon) {
    $.toast().reset('all');
    $.toast({
        text: text,
        icon: icon,
        showHideTransition: 'fade',
        allowToastClose: true,
        hideAfter: 1500,
        stack: false,
        position: 'top-right',
        textAlign: 'left',
        loader: true,
        loaderBg: '#9ec600',
    });
}
